package frontend.pages.admin.legalholiday;

import backend.model.other.LegalHoliday;
import backend.service.other.LegalHolidayService;
import frontend.core.TimeTrackingWebApplication;
import frontend.model.admin.LegalHolidayUIModel;
import frontend.pages.admin.base.AbstractManagingForm;
import frontend.components.base.ComponentFactory;
import org.apache.wicket.markup.html.WebMarkupContainer;

public class LegalHolidayForm extends AbstractManagingForm<LegalHolidayUIModel> {

    private static final String RESOURCE_KEY_FIELD_LABEL_DATE = "pages.admin.legalHoliday.form.date";
    private static final String RESOURCE_KEY_FIELD_LABEL_DESCRIPTION = "pages.admin.legalHoliday.form.description";
    private static final String RESOURCE_KEY_VALIDATION_DATE_ALREADY_CONFIGURED = "validation.form.legalHoliday.dateAlreadyConfigured";

    public LegalHolidayForm(String id, LegalHolidayUIModel holidayModel) {
        super(id, holidayModel);
    }

    @Override
    protected void constructFormContent() {
        WebMarkupContainer dateComponent = ComponentFactory.createDatePickerComponent("date",
                RESOURCE_KEY_FIELD_LABEL_DATE, uiModel);
        WebMarkupContainer descriptionComponent = ComponentFactory.createTextFieldComponent("description",
                RESOURCE_KEY_FIELD_LABEL_DESCRIPTION, uiModel);

        add(dateComponent, descriptionComponent);
    }

    @Override
    protected void doFormValidation() {
        boolean notEmpty = validateNotEmpty(uiModel, RESOURCE_KEY_FIELD_LABEL_DATE);
        if (notEmpty) {
            validateNotDuplicateDate();
        }
    }

    private void validateNotDuplicateDate() {
        LegalHolidayService service = TimeTrackingWebApplication.getService(LegalHolidayService.class);
        LegalHoliday dbLegalHoliday = service.getLegalHolidayByDate(uiModel.getDate());
        if (dbLegalHoliday != null) {
            addFieldValidationError(RESOURCE_KEY_FIELD_LABEL_DATE, RESOURCE_KEY_VALIDATION_DATE_ALREADY_CONFIGURED);
        }
    }

    @Override
    protected Class getResponsePage() {
        return LegalHolidayManagingPage.class;
    }
}
